#-*- encoding:utf-8 -*-
'''
Created on 2010-12-27

@author: Administrator
'''

from Models import db
from datetime import datetime
from flask import session,redirect,url_for
from functools import wraps

class user():
    '''
    用户管理
    '''
    @staticmethod
    def Login(loginid,loginpasswd):
        '''
        登陆
        @param loginid:登陆ID
        @param loginpasswd:登陆密码
        '''
        tmp=config.Get('LoginID')
        if tmp[0] != True or tmp[1] != loginid:
            return (False,u'用户名不正确!')

        tmp=config.Get('LoginPasswd')
        if tmp[0] != True or tmp[1] != loginpasswd:
            return (False,u'密码不正确!')

        tmp=config.Get('LoginNumber')
        if tmp[0] == True:
            config.Update('LoginNumber', int(tmp[1])+1)

        config.Update('LastLogin',datetime.now().strftime('%Y-%m-%d %X'))

        session['LoginID'] = loginid
        session['LoginTime'] = datetime.now().strftime('%Y-%m-%d %X')
        session['IsLogin'] = True

        return (True,u'登陆成功')

    @staticmethod
    def CheckLogin():
        if session.get('LoginID',None) == None:
            return (False,u'未登陆')

        if session.get('IsLogin',None) == None:
            return (False,u'未登陆')

        return (True,u'已登陆')

    @staticmethod
    def Authorize(f):
        '''
        检查授权
        '''
        @wraps(f)
        def func(*args, **kwargs):
            if user.CheckLogin()[0] == True:
                return f(*args, **kwargs)            
            else:
                return redirect(url_for('login'))
        return func

class config():
    '''
    配置管理
    '''
    @staticmethod
    def Add(config,value):
        '''
        添加配置
        @param config:配置名
        @param value:值
        '''
        if config is None or config =='':
            return (False,u'配置名不能为空')

        try:
            id = db.insert("config",config=config,value=value)
        except:
            return (False,u"数据库异常")

        return (True,id)

    @staticmethod
    def Update(config,newvalue):
        '''
        修改配置
        @param config:配置名
        @param newvalue:新值
        '''
        if config is None or config =='':
            return (False,u'配置名不能为空')

        try:
            num = db.update("config",where="config=$config",value=newvalue,vars={'config':config})
        except:
            return (False,u"数据库异常")

        return (True,num)#返回受影响的行数


    @staticmethod
    def Delete(config):
        '''
        删除配置
        @param config:配置名
        '''
        if config is None or config =='':
            return (False,u'配置名不能为空')

        try:
            num = db.delete("config",where="config=$config",vars=locals())
        except:
            return (False,u"数据库异常")

        return (True,num)

    @staticmethod
    def Get(config):
        '''
        获取配置
        @param config:配置名
        '''
        if config is None or config =='':
            return (False,u'配置名不能为空')

        try:
            rs = db.select("config",where="config=$config",vars=locals())
            return (True,rs[0].value)
        except:
            return (False,u"无此配置")

    @staticmethod
    def GetAll():
        '''
        获取全部配置
        '''
        try:
            rs = db.select("config")
            return (True,rs)
        except:
            return (False,u"数据库查询失败")


class categories():
    '''
    类别管理
    '''
    @staticmethod
    def Add(title):
        '''
        添加类别
        rs=categories.Add('类别标题')
        成功则返回
        (True,id)
        失败则返回
        (False,u'出错信息')

        @param title:类别标题
        '''
        if title is None or title =='':
            return (False,u'标题不能为空')

        try:
            id = db.insert("categories",title=title,articlecount=0)
        except:
            return (False,u'数据库异常错误')

        return (True,id)

    @staticmethod
    def Delete(id):
        '''
        删除类别
        成功则返回
        (True,'删除成功') 
        失败则返回
        (False,u'出错信息')
        @param id:类别的ID
        '''
        if id is None:
            return (False,u'id不能为空')
        
        t = db.transaction()
        try:
            db.delete('article_to_categories',where='categories_id=$id',vars=locals())
            db.delete('categories',where='id=$id',vars=locals())
        except:
            t.rollback()
            return (False,u'数据库异常错误')
        else:
            t.commit()

        return (True,u'删除成功')


    @staticmethod
    def Update(id,newtitle):
        '''
        修改类别名称
        @param id:类别的id
        @param newtitle:类别的新名称
        '''
        if id is None or id == '':
            return (False,u'id不能为空')

        if newtitle is None or newtitle == '':
            return (False,u'新名称不能为空')

        try:
            num = db.update('categories',where='id=$id',title=newtitle,vars=locals())#locals()就是返回当前的变量dict
        except:
            return (False,u'数据库异常错误')

        return (True,num)

    @staticmethod
    def Get(id):
        '''
        获取类别
        '''
        if id is None or id == '':
            return (False,u'id不能为空')
        
        try:
            rs = db.select("categories",where='id=$id',vars=locals())
            return (True,rs)
        except:
            return (False,u"数据库查询失败")


    @staticmethod
    def GetAll():
        '''
        获取全部类别
        '''
        try:
            rs = db.select("categories")
            return (True,rs)
        except:
            return (False,u"数据库查询失败")


class article():
    '''
    文章管理
    '''

    @staticmethod
    def Add(title,pubdate,author,content,mincontent,postdate=datetime.now().strftime('%Y-%m-%d %X'),ispublic=True,isedit=False,iscomment=True,commentnum=0,visitnum=0,fts_id=0):
        '''
        添加文章
        @param title:标题
        @param pubdate:发布日期
        @param author:作者
        @param content:内容
        @param mincontent:内容简介
        @param postdate:提交时间
        @param ispublic:是否公开
        @param isedit:是否编辑
        @param iscomment:是否允许评论
        @param commentnum:评论数
        @param visitnum:访问数
        @param fts_id:对应的全文搜索表ID
        '''
        if title is None or title == '':
            return (False,u'标题不能为空')

        if pubdate is None or pubdate == '':
            return (False,u'发布日期不能为空')

        try:
            id = db.insert("articles",title = title,pubdate = pubdate,author = author,content = content,mincontent = mincontent\
                           ,postdate = postdate,ispublic = ispublic,isedit = isedit,iscomment = iscomment,commentnum = commentnum,visitnum = visitnum,fts_id = fts_id)
        except:
            return (False,u'数据库异常错误')

        return (True,id)

    @staticmethod
    def Update(id,title,pubdate,author,content,mincontent,ispublic,isedit,iscomment,commentnum,visitnum,fts_id,postdate=datetime.now().strftime('%Y-%m-%d %X')):
        '''
        修改文章
        @param id:文章ID
        @param title:标题
        @param pubdate:发布日期
        @param author:作者
        @param content:内容
        @param mincontent:内容简介
        @param postdate:提交时间
        @param ispublic:是否公开
        @param isedit:是否编辑
        @param iscomment:是否允许评论
        @param commentnum:评论数
        @param visitnum:访问数
        @param fts_id:对应的全文搜索表ID
        '''
        if title is None or title == '':
            return (False,u'标题不能为空')

        if pubdate is None or pubdate == '':
            return (False,u'发布日期不能为空')

        try:
            num = db.update("articles",where="id=$id",title = title,pubdate = pubdate,author = author,content = content,mincontent = mincontent\
                           ,postdate = postdate,ispublic = ispublic,isedit = isedit,iscomment = iscomment,commentnum = commentnum,visitnum = visitnum,fts_id = fts_id,vars=locals())

        except:
            return (False,u'数据库异常错误')

        return (True,num)

    @staticmethod
    def Delete(id):
        '''
        删除文章
        @param id:文章ID
        '''
        if id is None or id == "":
            return (False,u'ID不能为空')


        try:
            num = db.delete("articles",where="id=$id",vars=locals())

        except:
            return (False,u'数据库异常错误')

        return (True,num)

    @staticmethod
    def Load(id):
        '''
        读取指定的一篇文章
        @param id:文章ID
        '''

        if id is None or id == "":
            return None

        try:
            rs = db.select("articles", where="id=$id", vars=locals())[0]
        except:
            return None

        return rs


class tag():
    '''
    标签表
    '''

    @staticmethod
    def Add(tagname):
        '''
        添加tag
        @param tagname:tag的名字
        '''
        if tagname is None or tagname == "":
            return (False,u"tag名不能为空")

        try:
            id = db.insert("tags",tag=tagname,renum=0)
        except:
            return (False,u"数据库异常错误")

        return (True,id)

    @staticmethod
    def Delete(id):
        '''
        删除tag
        @param id:tagid
        '''
        if id is None or id == "":
            return (False,u'ID不能为空')

        t = db.transaction()
        try:
            db.delete("article_to_tag",where="tag_id=$id",vars=locals())
            num = db.delete("tags",where="id=$id",vars=locals())

        except:
            t.rollback()
            return (False,u'数据库异常错误')
        else:
            t.commit()

        return (True,num)

    @staticmethod
    def Relations(article_id, tag_id=None, tagname=None):
        if article_id is None or article_id == "":
            return (False,u'文章id不能为空')
        
        t = db.transaction()
        if tagname is not None and tag_id is None:
            try:#尝试从数据库中调出tagname对应的id
                tag_id = db.select("tags",where="tag=$tag",vars={"tag":tagname})[0].id
            except:#如果不存在则新添加一个
                tag_id = tag.Add(tagname)
                if tag_id[0] == True:
                    tag_id=tag_id[1]
                else:
                    return (False,u'数据库异常错误')

        try:
            count = db.select("article_to_tag",what="count(0) as count",where="article_id=$article_id and tag_id=$tag_id",vars=locals())[0].count
            if count >= 1:
                t.rollback()#如果没有数据库的写入操作就回滚数据库
                return (True,u"已经关联")
            else:
                id = db.insert("article_to_tag",article_id=article_id,tag_id=tag_id)
                db.query("update tags set renum=renum+1 where id=$tag_id",vars=locals())#更新引用次数
        except:
            t.rollback()
            return (False,u'数据库异常错误，回滚数据')
        else:
            t.commit()
            return (True,u"关联成功")


    @staticmethod
    def GetAll():
        '''
        获取全部tag
        '''
        try:
            rs = db.select("tags")
            return (True,rs)
        except:
            return (False,u"数据库查询失败")

